# 用户登录模块
from flask import Blueprint, render_template, jsonify, flash, url_for, redirect, request
from web.models import LoginForm, RegisterForm, User
from flask_login import current_user, logout_user, login_user, login_required
from datetime import datetime

auth_view = Blueprint('auth', __name__)


@auth_view.route('/', methods=['POST', 'GET'])
@auth_view.route('/login', methods=['GET', 'POST'])
def login():
    login_form = LoginForm()
    if request.method == 'GET':
        if current_user.is_authenticated:
            flash('您已登录，请勿重复登录!', 'error')
            return redirect(url_for('index.index'))
        else:
            return render_template('auth/login.html', login_form=login_form)
    if request.method == 'POST':
        error_list = []
        if login_form.validate_on_submit():
            user = User.query.filter_by(username=login_form.username.data).first()
            if user and user.check_password(login_form.password.data):
                login_user(user)
                user.login_time = datetime.now()
                user.save()
                return jsonify({"code": 200, "msg": "用户登录成功，即将跳转~"})
            else:
                return jsonify({"code": 400, "msg": "用户名或密码错误！"})
        else:
            for field in login_form.errors.values():
                if "CSRF" in field[0]:
                    error_list.append("请刷新页面后尝试！")
                else:
                    error_list.append(field)
            return jsonify({"code": 40, "msg": error_list})


@auth_view.route('/register', methods=['POST', 'GET'])
def register():
    error_list = []
    register_form = RegisterForm()
    if request.method == 'GET':
        return render_template('auth/register.html', register_form=register_form)
    if request.method == 'POST':
        if register_form.validate_on_submit():
            user = User()
            user.username = register_form.username.data
            user.password = register_form.password.data
            user.save()
            return jsonify({"code": 200, "msg": "注册成功，请重新登录~"})
        else:
            for field in register_form.errors.values():
                if "CSRF" in field[0]:
                    error_list.append("请刷新页面后尝试！")
                else:
                    error_list.append(field)
            return jsonify({"code": 400, "msg": error_list})


@auth_view.route('/logout')
@login_required
def logout():
    logout_user()
    flash("退出登录成功！", "success")
    return redirect(url_for('index.index'))
